from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.http import JsonResponse


class TokenMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 从 Cookie 中获取 Token
        if 'login' in request.path:
            response = self.get_response(request)
            return response
        token = request.COOKIES.get('accessToken')
        if token:
            try:
                # 验证 Token
                jwt_auth = JWTAuthentication()
                validated_token = jwt_auth.get_validated_token(token)
                user = jwt_auth.get_user(validated_token)
                request.user = user  # 将用户对象附加到请求中
            except AuthenticationFailed:
                return JsonResponse({'code': 401, 'message': '无效的 Token'}, status=401)

        response = self.get_response(request)
        return response